import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Endstart
 * Date: 2021-05-21
 * Time: 2:12
 */
public class Replacement {
    int index;
    String before;
    String after;

    public static void main(String[] args) {

    }

    public String replaceRanges(String text, List<Replacement> replacements) {
        String copy = text;

        // 记录之前已替换的位置，在再次替换时，有时位置的startIndex要更新
        List<int[]> replaceRangeList = new ArrayList<>(); // int[]: startIndex and length

        for (Replacement replacement : replacements) {
            String prefix = copy.substring(0, replacement.index);
            String suffix = copy.substring(replacement.index);

            while (true) {
                //
                int index = suffix.indexOf(replacement.before);
                int length = replacement.before.length();
                int startIndex = prefix.length() + index;
                if (index == -1) {
                    break;
                }

                boolean canReplace = true;
                for (int[] replaceRange : replaceRangeList) {
                    if (!(startIndex + length < replaceRange[0] || replaceRange[0] + replaceRange[1] < startIndex)) {
                        // 两段有重叠，不能替换（会替换掉之前已经替换的内容）
                        canReplace = false;
                        break;
                    }
                }

                if (canReplace) {
                    suffix = suffix.substring(0, index) + replacement.after + suffix.substring(index + length);
                    int detaLength = replacement.after.length() - replacement.before.length();

                    if (detaLength != 0) {
                        for (int[] replaceRange : replaceRangeList) {
                            if (startIndex + length < replaceRange[0]) {
                                // 更新已替换位置后段在之前已替换数据的位置
                                replaceRange[0] += detaLength;
                            }
                        }
                    }

                    replaceRangeList.add(new int[]{startIndex, length});
                }

                copy = prefix + suffix;
            }

        }

        return copy;
    }

}
